package com.qdxht.dispenser.utils;

import android.content.Context;
import android.widget.Toast;

import com.qdxht.dispenser.base.manager.ActivityManager;
import com.qdxht.dispenser.interfaces.ExitCallback;
import com.hjq.toast.ToastUtils;

import java.util.Timer;
import java.util.TimerTask;


public class ExitUtil {
    private boolean isWaitingExit;
    private Timer mTimer;
    private static ExitUtil mInstance;
    private ExitUtil(){}
    public synchronized static ExitUtil getInstance(){
        if(mInstance==null){
            mInstance=new ExitUtil();
        }
        return mInstance;
    }

    /**
     * 退出应用的逻辑
     * @param context
     * @param callback 退出调用时的回调，以完成一些退出前必要的保存等工作。
     */
    public void exitLogic(Context context, ExitCallback callback){
        if(callback!=null){
            callback.callback();
        }
//        BaseApplication.checkUpdateNextTimeOpenApp = false;
//        ActivityManager.getInstance().popAllActivity();//remove all activity.
        ActivityManager.getInstance().finishAllActivities();//remove all activity.

//        System.exit(0);//system exit.
    }
    
    /**
     * called while back button click and there is no ui to back.
     */
    public void exit(Context context, ExitCallback callback) {
        if (isWaitingExit) {
            isWaitingExit = false;
            exitLogic(context,callback);
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
        } else {
            ToastUtils.show("再次点击退出");
            isWaitingExit = true;
            if (mTimer == null){
                mTimer = new Timer();
            }
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isWaitingExit = false;
                }
            }, 3000);
        }
    }
}
